package com.cicc.springboot.utile;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cicc.springboot.common.dto.R;
import com.cicc.springboot.entity.MaterialZmaraEntity;
import com.cicc.springboot.mapper.MaterialInformationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Set;

/**
 * 物料的Excel文件的导入导出监听器 （未使用）
 *
 * @ClassName MaterialExcelListener
 * @Description TODO
 * @Author 转轮王
 * @Date 2024/10/8 9:30
 * @Version 1.0
 */

@Component
public class MaterialExcelListener extends AnalysisEventListener<MaterialZmaraEntity> {

    private static final int BATCH_COUNT = 20;
    private List<MaterialZmaraEntity> list = new ArrayList<>();
    private final MaterialInformationMapper materialInformationMapper;
    private final StringBuilder responseMessage; // 用来记录响应信息

    // 通过构造方法传入 MaterialInformationMapper
    @Autowired
    public MaterialExcelListener(MaterialInformationMapper materialInformationMapper) {
        this.materialInformationMapper = materialInformationMapper;
        this.responseMessage = new StringBuilder(); // 在这里实例化 StringBuilder
    }

    @Override
    public void invoke(MaterialZmaraEntity data, AnalysisContext context) {
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    private R<String> saveData() {
        List<MaterialZmaraEntity> validData = new ArrayList<>();
        Set<String> materialNumberSet = new HashSet<>();

        // 遍历 Excel 数据，去除内部重复物料号
        for (MaterialZmaraEntity data : list) {
            if (materialNumberSet.add(data.getMatnr())) {
                validData.add(data);
            } else {
                responseMessage.append("Excel 中重复数据，保留一个，跳过: ").append(data.getMatnr()).append(" ");
            }
        }

        List<MaterialZmaraEntity> finalDataToInsert = new ArrayList<>();

        // 与数据库中的数据进行比对，插入不存在的数据
        for (MaterialZmaraEntity data : validData) {
            LambdaQueryWrapper<MaterialZmaraEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MaterialZmaraEntity::getMatnr, data.getMatnr());

            if (materialInformationMapper.selectCount(queryWrapper) == 0) {
                finalDataToInsert.add(data);
            } else {
                // 记录数据库已存在数据
                responseMessage.append("数据库中已存在，跳过: ").append(data.getMatnr()).append(" ");
            }
        }

        // 将不重复且数据库中不存在的数据插入数据库
        if (!finalDataToInsert.isEmpty()) {
            for (MaterialZmaraEntity valid : finalDataToInsert) {
                materialInformationMapper.insert(valid);
            }
            responseMessage.append("批量保存 ").append(finalDataToInsert.size()).append(" 条数据到数据库").append(" ");
        } else {
            responseMessage.append("无新的数据保存到数据库");
        }

        // 返回结果给前端
        return R.ok(responseMessage.toString());
    }

    // 新增一个方法用于获取响应消息
    public String getResponseMessage() {
        return responseMessage.toString();
    }
}
